package com.damage.common.oa.completeOrder;

import com.damage.common.config.ProcessDefinitionConfig;
import com.damage.common.entity.PurchaseInvoice;
import com.damage.common.service.IPublicService;
import com.damage.common.service.IWorkflowService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CompleteOrderWorkflowService implements IWorkflowService<PurchaseInvoice>{

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private IPublicService publicService;

    @Override
    @Transactional(readOnly = true)
    public List<PurchaseInvoice> findTodoTasks(String userId) {
        List<PurchaseInvoice> results = new ArrayList<>();

        //根据用户ID查询关联的业务实体类
        List<Task> tasks = taskService.createTaskQuery()
                .taskCandidateOrAssigned(userId)
                .list();
        for (Task task : tasks) {
            String processInstanceId = task.getProcessInstanceId();
            //查找任务流程实例ID对应并且处于活动状态的流程实例
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .processDefinitionKey(ProcessDefinitionConfig.COMPLETE_ORDER)
                    .active()
                    .singleResult();
            if (processInstance == null) {
                //找不到流程实例，即该流程实例不在活动状态
                continue;
            }
            //获得业务实体的id
            String businessKey = processInstance.getBusinessKey();
            if (businessKey == null) {
                //找不到业务实体的id，即该业务实体不存在
                continue;
            }
            PurchaseInvoice purchaseInvoice = publicService.findPurchaseInvoiceById(Integer.parseInt(businessKey));
            purchaseInvoice.setTask(task);
            results.add(purchaseInvoice);
        }
        return results;
    }

    @Override
    @Transactional(readOnly = true)
    public List<PurchaseInvoice> findRunningProcessInstaces() {
        List<PurchaseInvoice> results = new ArrayList<>();
        //查找流程实例，条件是：流程定义的id是completeOrder，激活中，以流程实例id降序排序。
        List<ProcessInstance> list = runtimeService.createProcessInstanceQuery()
                .processDefinitionKey(ProcessDefinitionConfig.COMPLETE_ORDER)
                .active()
                .orderByProcessInstanceId()
                .desc()
                .list();
        //关联业务实体
        for (ProcessInstance processInstance : list) {
            String businessKey = processInstance.getBusinessKey();
            if (businessKey == null) {
                continue;
            }
            PurchaseInvoice purchaseInvoice = publicService.findPurchaseInvoiceById(Integer.parseInt(businessKey));
            purchaseInvoice.setProcessInstance(processInstance);
            purchaseInvoice.setProcessDefinition(getProcessDefinition(processInstance.getProcessDefinitionId()));

            //设置当前任务信息
            List<Task> tasks = taskService.createTaskQuery()
                    .processInstanceId(processInstance.getId())
                    .active()
                    .orderByTaskCreateTime()
                    .desc()
                    .list();
            purchaseInvoice.setTask(tasks.get(0));

            results.add(purchaseInvoice);
        }
        return results;
    }

    @Override
    @Transactional(readOnly = true)
    public List<PurchaseInvoice> findFinishedProcessInstaces() {
        List<PurchaseInvoice> results = new ArrayList<>();
        //查找历史流程实例，条件是：流程定义的id是completeOrder，已完成，以流程实例结束时间降序排序。
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery()
                .processDefinitionKey(ProcessDefinitionConfig.MAKE_PURCHASE_PLAN)
                .finished()
                .orderByProcessInstanceEndTime()
                .desc()
                .list();

        //关联业务实体
        for (HistoricProcessInstance historicProcessInstance : list) {
            String businessKey = historicProcessInstance.getBusinessKey();
            PurchaseInvoice purchaseInvoice = publicService.findPurchaseInvoiceById(Integer.parseInt(businessKey));
            purchaseInvoice.setProcessDefinition(getProcessDefinition(historicProcessInstance.getProcessDefinitionId()));
            purchaseInvoice.setHistoricProcessInstance(historicProcessInstance);
            results.add(purchaseInvoice);
        }
        return results;
    }

    /**
     * 通过流程定义id获得流程定义对象
     *
     * @param processDefinitionId 流程定义ID
     * @return
     */
    protected ProcessDefinition getProcessDefinition(String processDefinitionId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        return processDefinition;
    }
}
